package com.ruoyi.controller;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import cn.binarywang.wx.miniapp.bean.WxMaPhoneNumberInfo;
import cn.binarywang.wx.miniapp.bean.WxMaUserInfo;
import com.ruoyi.common.core.domain.AjaxResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

@Slf4j
@Api(tags = "小程序相关")
@RestController
@RequestMapping("/wx/miniapp")
public class MiniAppController {
    @Resource
    private WxMaService wxMaService;

    @ApiOperation("用户小程序登录")
    @PostMapping("/login")
    public AjaxResult login(@ApiParam("临时登录凭证") @RequestParam String code) {
        try {
            // 通过 code 获取 session 信息
            WxMaJscode2SessionResult sessionResult = wxMaService.getUserService().getSessionInfo(code);

            // 获取用户的 openid
            String openid = sessionResult.getOpenid();

            // 获取 session_key
            String sessionKey = sessionResult.getSessionKey();

            return AjaxResult.success();
        } catch (WxErrorException e) {
            return AjaxResult.error("登录失败: " + e.getError().getErrorMsg());
        }
    }

    @ApiOperation("获取用户信息")
    @PostMapping("/info")
    public AjaxResult getUserInfo(@ApiParam("会话密钥") @RequestParam String sessionKey, @ApiParam("加密数据") @RequestParam String encryptedData, @ApiParam("初始向量") @RequestParam String iv) {
        // 使用会话密钥、加密数据和初始向量解密获取用户信息
        WxMaUserInfo userInfo = wxMaService.getUserService().getUserInfo(sessionKey, encryptedData, iv);
        return AjaxResult.success(null, userInfo);
    }

    @ApiOperation("获取手机号信息")
    @PostMapping("/phone")
    public AjaxResult getPhoneNumber(@ApiParam("会话密钥") @RequestParam String sessionKey, @ApiParam("加密数据") @RequestParam String encryptedData, @ApiParam("初始向量") @RequestParam String iv) {
        // 使用会话密钥、加密数据和初始向量解密获取手机号信息
        WxMaPhoneNumberInfo phoneNumberInfo = wxMaService.getUserService().getPhoneNoInfo(sessionKey, encryptedData, iv);
        String phoneNumber = phoneNumberInfo.getPhoneNumber();
        return AjaxResult.success(null, phoneNumber);
    }
}
